﻿using FreeSql;
using System;
using WebApiOrm.Provider;
using WebApiOrm.Provider.FreeSqlSqlite;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// OrmBuilder扩展
    /// 扩展添加具体的Orm
    /// </summary>
    public static class OrmBuilderExtensions
    {
        /// <summary>
        /// 添加FreeSql的Orm
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IOrmBuilder AddFreeSql(this IOrmBuilder builder, string ormName)
        {
            builder.Services.AddOrmProvider<FreeSqlOrmProvider>(ormName);
            builder.Services.AddSingleton(provider =>
            {
                var dataType = builder.DatabaseType switch
                {
                    DatabaseType.Sqlite => DataType.Sqlite,
                    DatabaseType.SqlServer => DataType.SqlServer,
                    DatabaseType.PostgreSQL => DataType.PostgreSQL,
                    _ => throw new NotSupportedException(),
                };

                var fsql = new FreeSqlBuilder()
                    .UseConnectionString(dataType, builder.ConnectionString)
                    .UseNoneCommandParameter(true)
                    .UseAutoSyncStructure(false)
                    .Build();
                return fsql;
            });
            return builder;
        }
    }
}
